const nodemailer = require('nodemailer');
const config = require('./config');
const winston = require('winston');

// 创建邮件传输对象
const transporter = nodemailer.createTransport({
    service: 'QQ',
    auth: {
        user: config.email.user,
        pass: config.email.pass
    }
});

// 验证邮件配置
async function verifyEmailConfig() {
    try {
        await transporter.verify();
        winston.info('邮件服务配置验证成功');
        return true;
    } catch (error) {
        winston.error('邮件服务配置验证失败:', error);
        return false;
    }
}

// 发送验证码邮件
async function sendVerificationEmail(email, code) {
    try {
        // 验证邮件配置
        const isConfigValid = await verifyEmailConfig();
        if (!isConfigValid) {
            throw new Error('邮件服务配置无效，请检查邮箱设置');
        }

        const mailOptions = {
            from: config.email.user,
            to: email,
            subject: '登录验证码',
            html: `
                <div style="max-width: 600px; margin: 0 auto; padding: 20px; font-family: Arial, sans-serif;">
                    <h2 style="color: #333;">登录验证码</h2>
                    <p style="color: #666; font-size: 16px;">您的验证码是：</p>
                    <div style="background-color: #f5f5f5; padding: 15px; border-radius: 5px; text-align: center; margin: 20px 0;">
                        <span style="font-size: 24px; font-weight: bold; color: #007bff;">${code}</span>
                    </div>
                    <p style="color: #666; font-size: 14px;">验证码有效期为5分钟，请尽快使用。</p>
                    <p style="color: #999; font-size: 12px; margin-top: 20px;">如非本人操作，请忽略此邮件。</p>
                </div>
            `
        };

        winston.info('正在发送验证码邮件', { to: email });
        const info = await transporter.sendMail(mailOptions);
        winston.info('验证码邮件发送成功', { messageId: info.messageId });
        return info;
    } catch (error) {
        winston.error('发送验证码邮件失败:', { error: error.message, email });
        throw new Error(`发送邮件失败: ${error.message}`);
    }
}

module.exports = {
    sendVerificationEmail,
    verifyEmailConfig
}; 